package www.ym.com.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import www.ym.com.common.BaseContext;
import www.ym.com.utils.JWTUtils;

/**
 * 拦截器，检查用户是否完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 进行路径匹配，判断本次请求是否需要放行
     *
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean check(String[] urls, String requestURL) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURL);
            if (match) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断该请求是否需要token
     *
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean checkToken(String[] urls, String requestURL) {

        for (String url : urls) {
            if (url.equals(requestURL)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到请求：{}", request.getRequestURI());
        //1.获取本次请求的URL
        String requestURL = request.getRequestURI();

//        定义不需要处理的请求路径
        String[] urls = new String[]{
                "/user/register",
                "/user/login",
                "/user/reset",
                "/staff/password",
                "/staff/login",
//                "/employee/login",
//                "/employee/logout",
//                "/backend/**",
//                "/front/**",
//                "/common/**",
//                "/role/**",
//                "/user/**",
//                "/note/**",
//                "/role/**",
//                "/department/**",
//                "/staff/**",
//                "/category/**",
//                "/dishFlavor/**",
//                "/dish/**",
//                "/setmeal/**",
//                "/company/**",
//                "/consum/**",
//                "/menu/**",
//                "/roleMenu/**",
//                "/shoppingCart/**",
//                "/address/**",
//                "/account/**",
//                "/log/**",
//                "/order/**",
        };


//
//        2.判断本次请求是否需要处理
        boolean check = checkToken(urls, requestURL);
//        3.如果不需要处理，则直接放行
        if (check) {
            log.info("是否进入" + 1111);
            filterChain.doFilter(request, response);
            return;
        }
        //获取token，判断是否登录
        log.info("是否出来" + 1111);
        log.info("请求体" + request.getContentType());

        String token = request.getHeader("Authorization");
        log.info("打印token" + token);
        if (!StringUtils.isEmpty(token)) {
            log.info("打印s" + 111);
            Claims claims = JWTUtils.parseJWT(token);
            log.info("有token" + 111);

            String s = JSONObject.toJSONString(claims);
            filterChain.doFilter(request, response);
            return;
        }
//        filterChain.doFilter(request, response);
        //5.如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
        log.info("进入最后一步" + "是");
//        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(R.error("NOTLOGIN")));
        log.info("进入最后一步" + "否");
    }
}
